from functools import wraps
from flask import request, redirect, url_for, render_template
from flask_login import current_user
from app.utils import custom_jsonify

def handle_errors(app):
    @app.errorhandler(404)
    def not_found_error(error):
        if request.is_json:
            return custom_jsonify({"msg": "failed", "error": "资源不存在"}, 404)
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def internal_error(error):
        if request.is_json:
            return custom_jsonify({"msg": "failed", "error": "服务器内部错误"}, 500)
        return render_template('500.html'), 500

def auth_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated:
            if request.is_json:
                return custom_jsonify({
                    "msg": "failed",
                    "error": "需要登录"
                }, 401)
            return redirect(url_for('auth.login'))
        return f(*args, **kwargs)
    return decorated_function 